<?php


namespace App\Admin\Controllers;

use App\Constants\SmsConstant;
use App\Models\Settings;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Tab;

class SmsSettingController extends AdminController
{
    public function index(Content $content)
    {
        $tab = Tab::make();
        $tab->add('短信配置', $this->grid(), true);
        $tab->addLink('模板管理', admin_route('sms_tpl.index'));
        $tab->addLink('发送记录', admin_route('sms_log.index'));
        return $content->body($tab->withCard());
    }

    protected function grid()
    {
        $form = new Form();

        $form->action(admin_route('sms_setting.store'));
        $form->disableHeader();

        $setting = getSettings(SmsConstant::GROUP);

        $form->select(SmsConstant::SMS_DRIVER, '驱动方式')
            ->options(['aliyun' => '阿里云'])
            ->when('aliyun', function (Form $form) use ($setting) {
                $form->text(SmsConstant::ALIYUN_APP_SIGN_NAME, '短信签名')->value($setting[SmsConstant::ALIYUN_APP_SIGN_NAME] ?? '');
                $form->text(SmsConstant::ALIYUN_APP_KEY, '公钥信息')->value($setting[SmsConstant::ALIYUN_APP_KEY] ?? '');
                $form->text(SmsConstant::ALIYUN_APP_SECRET_KEY, '私钥信息')->value($setting[SmsConstant::ALIYUN_APP_SECRET_KEY] ?? '');
            })
            ->value($setting[SmsConstant::SMS_DRIVER] ?? 'aliyun');

        $form->number(SmsConstant::MAX_EXPIRE, '过期时间（秒）')->help('0表示不过期，建议填1800或900')->value($setting[SmsConstant::MAX_EXPIRE ?? '']);
        $form->number(SmsConstant::MAX_COUNT, '最多失败次数')->help('0表示不限制，建议填3，表示3次验证失败后验证码得重新发')->value($setting[SmsConstant::MAX_COUNT ?? '']);

        $form->disableResetButton();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();

        return $form;
    }

    public function store()
    {
        $post = request()->post();
        unset($post['_token']);

        $group = SmsConstant::GROUP;

        try {
            foreach ($post as $key => $item) {
                Settings::where(['group' => $group, 'name' => $key])->update(['value' => $item]);
            }
        }catch (\Exception $e) {
            return JsonResponse::make()->error('保存失败');
        } finally {
            flushSettings($group);
        }

        return JsonResponse::make()->success('保存成功！')->refresh();
    }
}
